import React, { useEffect, useState, useCallback } from "react";
import style from "./Index.module.css";
import request from "../../api/request";
import fen from "../../assets/fenxiang03.jpg";
import { Tabs } from "antd-mobile";
import { FloatingBubble } from 'antd-mobile'
import { MessageFill } from 'antd-mobile-icons'
import { StarOutline, EyeOutline, LikeOutline } from "antd-mobile-icons";
import { useNavigate } from "react-router-dom";

interface ArticleItem {
  doctorid: number;
  doctorname: string;
  doctorstate: string;
  doctoradministre: string;
  texttitle: string;
  textimage: string;
  doctorimage: string;
  textdescword: string;
  doctordescword: string;
  doctorgood: number;
  doctoradmin: number;
}


// 虚拟列表项组件
const VirtualListItem = ({ index, style: itemStyle, data, onItemClick }: { 
  index: number; 
  style: React.CSSProperties; 
  data: ArticleItem[]; 
  onItemClick: (id: number) => void;
}) => {
  const item = data[index];
  if (!item) return <div style={itemStyle}>加载中...</div>;

  return (
    <div style={itemStyle} onClick={() => onItemClick(item.doctorid)}>
      <div className={style.imgavatar}>
        <img src={item.doctorimage} alt="" />
        <div className={style.imgright}>
          <span><b>{item.doctorname}</b></span>
          <span className={style.doctor}>{item.doctorstate}</span>
          <p className={style.imgbottom}>{item.doctoradministre}</p>
        </div>
      </div>

      <p className={style.why}>
        <b>{item.texttitle}</b>
      </p>

      <div className={style.imgbox}>
        <img src={item.textimage} alt="" />
        <img src={item.doctorimage} alt="" />
        <img src={item.textimage} alt="" />
      </div>

      <div className={style.textbox}>
        <p className={style.textmsg}>{item.textdescword}</p>
        <span className={style.anli}>{item.doctordescword?.substring(0, 7)}</span>
      </div>

      <div className={style.spanthree}>
        <span>
          <EyeOutline />
          {item.doctorgood}
        </span>
        <span>
          <StarOutline />
          {item.doctoradmin}
        </span>
        <span>
          <LikeOutline />
          {item.doctoradmin}
        </span>
      </div>
    </div>
  );
};

function Index() {
  const [articleList, setArticleList] = useState<ArticleItem[]>([]);
  const [articleList1, setArticleList1] = useState<ArticleItem[]>([]);
  const [pageCode, setPageCode] = useState<number>(1);
  const [pageCode1, setPageCode1] = useState<number>(1);
  const [pageSize] = useState<number>(10);
  const [hasMore, setHasMore] = useState(true);
  const [hasMore1, setHasMore1] = useState(true);
  const [loading, setLoading] = useState(false);
  const [loading1, setLoading1] = useState(false);
  const navigate = useNavigate();

  const getArticleList = useCallback(async () => {
    console.log("getArticleList called");
    
    setLoading(true);
    try {
      const res = await request.get("/api/book/list", {
        params: {
          pageCode,
          pageSize,
        },
      });
      console.log("患者案例 - 最新", res);
      console.log("res.data:", res.data);
      
      // API响应结构：res.data 直接是数组
      if (res.data && Array.isArray(res.data)) {
        console.log("Setting article list, data length:", res.data.length);
        const newData = res.data;
        console.log("New data:", newData);
        
        setArticleList(prev => {
          console.log("Previous articleList length:", prev.length);
          const newList = [...prev, ...newData];
          console.log("New article list length:", newList.length);
          return newList;
        });
        
        setPageCode(prev => prev + 1);
        
        if (res.data.length < pageSize) {
          setHasMore(false);
        }
      } else {
        console.log("API response is not an array:", res.data);
      }
    } catch (error) {
      console.error("加载数据失败:", error);
    } finally {
      setLoading(false);
    }
  }, [pageCode, pageSize]);

  const getArticleList1 = useCallback(async () => {
    console.log("getArticleList1 called");
    
    setLoading1(true);
    try {
      const res = await request.get("/api/book/list", {
        params: {
          pageCode: pageCode1 + 100, // 使用不同的起始页码来获取不同的数据
          pageSize: 20,
        },
      });
      console.log("患者案例 - 最热", res);
      console.log("res.data:", res.data);
      
      // API响应结构：res.data 直接是数组
      if (res.data && Array.isArray(res.data)) {
        console.log("Setting article list1, data length:", res.data.length);
        const newData = res.data;
        console.log("New data1:", newData);
        
        setArticleList1(prev => {
          console.log("Previous articleList1 length:", prev.length);
          const newList = [...prev, ...newData];
          console.log("New article list1 length:", newList.length);
          return newList;
        });
        
        setPageCode1(prev => prev + 1);
        
        if (res.data.length < 20) {
          setHasMore1(false);
        }
      } else {
        console.log("API response is not an array:", res.data);
      }
    } catch (error) {
      console.error("加载数据失败:", error);
    } finally {
      setLoading1(false);
    }
  }, [pageCode1]);

  useEffect(() => {
    getArticleList();
    getArticleList1();
  }, []); // 只在组件挂载时执行一次


  // 滚动监听函数
  const handleScroll = useCallback((e: React.UIEvent<HTMLDivElement>) => {
    const target = e.target as HTMLDivElement;
    const { scrollTop, scrollHeight, clientHeight } = target;
    
    // 当滚动到底部附近时（距离底部100px以内）触发加载
    if (scrollTop + clientHeight >= scrollHeight - 100) {
      // 根据当前激活的标签页决定加载哪个数据
      const activeTab = document.querySelector('.adm-tabs-tab-active');
      if (activeTab) {
        const tabText = activeTab.textContent;
        if (tabText === '最新' && hasMore && !loading) {
          console.log("触发加载更多 - 最新");
          getArticleList();
        } else if (tabText === '最热' && hasMore1 && !loading1) {
          console.log("触发加载更多 - 最热");
          getArticleList1();
        }
      }
    }
  }, [hasMore, loading, hasMore1, loading1, getArticleList, getArticleList1]);

  const goTojin=()=>{

  }

  const goArtdetail = (id: number) => {
    navigate(`/orderDetail/${id}`)
  }

  return (
    <div>
      <h3 style={{ textAlign: "center", marginTop: 15 }}>患者案例</h3>
      <img className={style.fenimg} src={fen} alt="" />

      <div className={style.tabs}>
        <Tabs>
          <Tabs.Tab title="最新" key="new">
            <div style={{ height: '70vh' }}>
              {articleList.length > 0 ? (
                <div style={{ height: '100%', overflow: 'auto' }} onScroll={handleScroll}>
                  {articleList.map((_, index) => (
                    <div key={index} style={{ padding: '10px', borderBottom: '1px solid #eee' }}>
                      <VirtualListItem
                        index={index}
                        style={{}}
                        data={articleList}
                        onItemClick={goArtdetail}
                      />
                    </div>
                  ))}
                  {loading && (
                    <div style={{ textAlign: 'center', padding: '20px' }}>
                      加载中...
                    </div>
                  )}
                </div>
              ) : (
                <div style={{ textAlign: 'center', padding: '20px' }}>
                  {loading ? '加载中...' : '暂无数据'}
                </div>
              )}
            </div>
          </Tabs.Tab>
          <Tabs.Tab title="最热" key="hot">
            <div style={{ height: '70vh' }}>
              {articleList1.length > 0 ? (
                <div style={{ height: '100%', overflow: 'auto' }} onScroll={handleScroll}>
                  {articleList1.map((_, index) => (
                    <div key={index} style={{ padding: '10px', borderBottom: '1px solid #eee' }}>
                      <VirtualListItem
                        index={index}
                        style={{}}
                        data={articleList1}
                        onItemClick={goArtdetail}
                      />
                    </div>
                  ))}
                  {loading1 && (
                    <div style={{ textAlign: 'center', padding: '20px' }}>
                      加载中...
                    </div>
                  )}
                </div>
              ) : (
                <div style={{ textAlign: 'center', padding: '20px' }}>
                  {loading1 ? '加载中...' : '暂无数据'}
                </div>
              )}
            </div>
          </Tabs.Tab>
        </Tabs>
      </div>

      <FloatingBubble
        style={{
          '--initial-position-bottom': '74px',
          '--initial-position-right': '4px',
          '--edge-distance': '24px',
        }}
        onClick={()=>goTojin()}
      >
        <MessageFill fontSize={32} />
      </FloatingBubble>
    </div>
  );
}

export default Index;
